keep-alive
keepalive
是 Vue
内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染,也就是所谓的组件缓存。
使用场景:数据不是动态改变的,组件没有必要多次初始化,使组件的状态维持不变,在下一次展示时,无需重新初始化组件。
<div>
<div id="dynamic-component-demo">
<button
v-for="tab in tabs" // 循环
v-bind:key="tab" // key
v-on:click="currentTab=tab" // 点击事件
>
{{ tab }}
</button>
</div>
<!-- 数据持久化 -->
<keep-alive>
<component
class="tab"
v-bind:is="currentTabComponent" // 多组件只渲染一个
></component>
</keep-alive>
</div>
new Vue({
el:'#dynamic-component-demo',
data:{
currentTab:"Posts"
tabs:["Posts","Archive"]
},
computed:{
currentTabComponent:function () {
return 'tab-'+this.currentTab.toLowerCase()
}
}
})
tab-posts 组件
Vue.component('tab-posts',{
data:function(){
return {
// Posts数据
selectedPost: null,
posts:[
{id:1,title:"Cat",content:"Cat content"},
{id:2,title:"Hipster",content:"Hipster content"},
{id:3,title:"Cupcake",content:"Cupcake content"}
]
//
}
}
})
tab-archive 组件
Vue.component('tab-archive',{
template: "<div>Archive component</div>"
})
官方预览地址:keep-alive